import React, { Component } from 'react';
// import BpmnViewer from 'bpmn-js';
import { CustomViewer } from './view';
import { message } from 'antd';
import PropTypes from 'prop-types';
import SequenceFlowPannel from '../sequenceFlowPannel';
import NoSelectNode from '../noSelectNode';
import UserTaskPannel from '../userTaskPannel';
import OtherNodePanel from '../otherNodePanel';
import styles from '../editor/BpmnEditor/sources/Bpmn.less';
import ViewTVools from './viewTools';
import { getSequenceFlowChild, getNodeAttr, getTaskType, getStation } from '../commonFunc';
import { connect } from 'dva';
class Viewer extends Component {
  // props默认值
  static defaultProps = {
    diagramXML: undefined, // 默认无流程图数据
    height: '100%', // 默认高度占父容器100%
    width: '100%', // 默认宽度占父容器100%
  };

  state = {
    scale: 1, // 流程图比例
    type: undefined, // 点击节点类型
    id: undefined, // 节点ID
    name: undefined, // 节点名称
    condition: undefined, // 节点条件（通过 or 驳回，仅在type为SequenceFlow时生效）
    taskType: undefined, // 审批类型
    station: undefined, // 岗位
    user: undefined, // 用户
  };

  sequenceId = 'bpmn:SequenceFlow'; // xml中网关条件的key值
  userTask = 'bpmn:UserTask'; // xml中usertask key值
  loadXML = (xml) => {
    this.viewer.importXML(xml, (err) => {
      if (err) {
        message.error('流程图加载失败！');
        return;
      } else {
        let canvas = this.viewer.get('canvas');
        canvas.zoom('fit-viewport', 'auto'); //流程图自适应画布
      }
    });
  };

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.viewer) {
      if (this.props.diagramXML !== nextProps.diagramXML) {
        this.loadXML(nextProps.diagramXML);
      }
    }
  }

  componentDidMount() {
    this.queryStationUserList(); //查询岗位和用户列表
    this.viewer = new CustomViewer({
      container: '#canvas',
      height: this.props.height,
      width: this.props.width,
    });

    this.loadXML(this.props.diagramXML);
    var parser = new DOMParser();
    this.xmlDoc = parser.parseFromString(this.props.diagramXML, 'text/xml');

    // 添加节点点击事件
    let eventBus = this.viewer.get('eventBus');
    eventBus.on('element.click', (e) => {
      let node = e.element.businessObject;
      if (node.$type == this.sequenceId && node.sourceRef.$type === 'bpmn:ExclusiveGateway') {
        this.setState({
          type: this.sequenceId,
          id: node.id,
          name: node.name,
          condition: getSequenceFlowChild(this.xmlDoc, node.id),
          expression: node.conditionExpression,
        });
      } else if (node.$type == this.userTask) {
        let taskType = getTaskType(this.xmlDoc, node.id);
        this.setState({
          type: this.userTask,
          id: node.id,
          name: node.name,
          taskType: taskType,
          station: getStation(this.xmlDoc, node.id, taskType),
          user: getNodeAttr(this.xmlDoc, node.id, 'activiti:assignee'),
        });
      } else if (node.$type !== 'bpmn:Process') {
        this.setState({
          type: 'other',
          id: node.id,
          name: node.name,
        });
      }
    });

    // 删除 bpmn logo
    const bjsIoLogo = document.querySelector('.bjs-powered-by');
    while (bjsIoLogo.firstChild) {
      bjsIoLogo.removeChild(bjsIoLogo.firstChild);
    }
  }

  //查询岗位和用户列表
  queryStationUserList = () => {
    this.props.dispatch({
      type: 'bpmnM/getStationList',
      payload: {},
      callback: (data) => {
        this.setState({
          stationList: [...data],
        });
      },
    });
    this.props.dispatch({
      type: 'bpmnM/getUserList',
      payload: {},
      callback: (data) => {
        this.setState({
          userList: [...data],
        });
      },
    });
  };
  // “重置”、“放大”、“缩小”按钮
  handleZoom = (radio) => {
    const newScale = !radio ? 1.0 : this.state.scale + radio <= 0.2 ? 0.2 : this.state.scale + radio;

    this.viewer.get('canvas').zoom(newScale);
    this.setState({
      scale: newScale,
    });
  };
  render() {
    let { type } = this.state;
    let height = this.props.height || '500px';
    return (
      <div style={{ height: height }}>
        <div style={{ height: '100%', border: '1px solid #E4E7EE', overflow: 'auto' }}>
          <div className={styles.bpmnTilte}>流程图</div>
          <div id='canvas' style={{ height: `calc(${height} - 100px)` }} />
          {/* 右上角工具栏定义 */}
          <ViewTVools
            // onZoomReset={() => this.handleZoom()}   // 重置
            onZoomIn={() => this.handleZoom(0.1)} // 放大
            onZoomOut={() => this.handleZoom(-0.1)} // 缩小
          />
        </div>
        {type === undefined && <NoSelectNode />}
        {type === this.sequenceId && (
          <SequenceFlowPannel
            id={this.state.id}
            name={this.state.name}
            condition={this.state.condition}
            isOrder={this.props.isOrder} //指令情况下
            expression={this.state.expression}
            flowType={this.props.flowType}
            flowChildType={this.props.flowChildType}
          />
        )}
        {type === this.userTask && (
          <UserTaskPannel
            id={this.state.id}
            name={this.state.name}
            taskType={this.state.taskType}
            station={this.state.station}
            user={this.state.user}
            stationList={this.state.stationList}
            userList={this.state.userList}
          />
        )}
        {type === 'other' && <OtherNodePanel id={this.state.id} name={this.state.name} />}
      </div>
    );
  }
}

// props类型
Viewer.propsTypes = {
  diagramXML: PropTypes.string, // 流程图数据
  height: PropTypes.string, // 高度
  width: PropTypes.string, // 宽度
  isOrder: PropTypes.bool, // 当前模式是回购指令
};

export default connect(({ bpmnM }) => ({ bpmnM }))(Viewer);
